const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');

// 用户信息 JSON 文件路径
const usersFilePath = path.join(__dirname, '../json/users.json');

// 读取 JSON 文件
const readJsonData = (filePath) => {
    const data = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(data);
};

// 写入 JSON 文件
const writeJsonData = (filePath, data) => {
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
};

// 去除用户对象中的 password 字段
const removePasswordField = (user) => {
    const {password, ...userWithoutPassword} = user;
    return userWithoutPassword;
};

// 验证 JWT token 中间件
const verifyToken = (req, res, next) => {
    const token = req.headers['authorization']?.split(' ')[1];

    if (!token) {
        return res.status(401).json({
            code: 1,
            message: '未提供 token'
        });
    }

    jwt.verify(token, 'your_secret_key', (err, decoded) => {
        if (err) {
            return res.status(401).json({
                code: 1,
                message: '认证失败，请重新登陆'
            });
        }
        req.user = decoded;
        next();
    });
};

// 获取用户列表，支持筛选
exports.getUsers = [verifyToken, (req, res) => {
    const {nickName, state, username, pageNum = 1, pageSize = 10} = req.query;

    let users = readJsonData(usersFilePath);

    // 条件筛选
    if (nickName) {
        users = users.filter(user => user.nickName.includes(nickName));
    }
    if (state) {
        users = users.filter(user => user.state === parseInt(state));
    }
    if (username) {
        users = users.filter(user => user.username.includes(username));
    }

    const total = users.length; // 记录总条数
    const page = parseInt(pageNum);
    const size = parseInt(pageSize);

    const startIndex = (page - 1) * size;
    const endIndex = startIndex + size;

    const pagedUsers = users.slice(startIndex, endIndex);

    return res.json({
        code: 0,
        message: '用户数据获取成功',
        content: pagedUsers,
        total,
        pageNum: page,
        pageSize: size,
    });
}];

// 新增用户
exports.addUser = [verifyToken, (req, res) => {
    let {username, password = '123456', email, num, nickName, state} = req.body;

    // 简单校验
    if (!username || !email || !num || !nickName) {
        return res.status(400).json({
            code: 1,
            message: '缺少必要字段 (username, email, num, nickName)'
        });
    }

    state = state ? parseInt(state) : 1; // 默认状态 1

    let users = readJsonData(usersFilePath);

    // 检查账号是否已存在
    const existUser = users.find(user => user.username === username);
    if (existUser) {
        return res.status(409).json({
            code: 1,
            message: '账号已存在'
        });
    }

    const newId = users.length > 0 ? users[users.length - 1].id + 1 : 1;

    const newUser = {
        id: newId,
        username,
        password,
        email,
        num,
        state,
        nickName
    };

    users.push(newUser);
    writeJsonData(usersFilePath, users);

    // const newUserWithoutPassword = removePasswordField(newUser);

    res.status(201).json({
        code: 0,
        message: '用户添加成功',
        content: newUser
    });
}];

// 编辑
exports.editUser = [verifyToken, (req, res) => {
    const {id, password, email, num, state, nickName} = req.body;

    if (!id) {
        return res.status(400).json({
            code: 1,
            message: '缺少用户 id'
        });
    }

    let users = readJsonData(usersFilePath);
    const userIndex = users.findIndex(user => user.id === parseInt(id));

    if (userIndex === -1) {
        return res.status(404).json({
            code: 1,
            message: '用户不存在'
        });
    }

    // 更新字段（只更新给出的字段）
    if (password !== undefined) users[userIndex].password = password;
    if (email !== undefined) users[userIndex].email = email;
    if (num !== undefined) users[userIndex].num = num;
    if (state !== undefined) users[userIndex].state = parseInt(state);
    if (nickName !== undefined) users[userIndex].nickName = nickName;

    writeJsonData(usersFilePath, users);

    res.json({
        code: 0,
        message: '用户更新成功',
        content: users[userIndex]
    });
}];

// 删除
exports.deleteUser = [verifyToken, (req, res) => {
    const {id} = req.body;

    if (!id) {
        return res.status(400).json({
            code: 1,
            message: '缺少用户 id'
        });
    }

    let users = readJsonData(usersFilePath);
    const initialLength = users.length;

    users = users.filter(user => user.id !== parseInt(id));

    if (users.length === initialLength) {
        return res.status(404).json({
            code: 1,
            message: '用户不存在或已被删除'
        });
    }

    writeJsonData(usersFilePath, users);

    res.json({
        code: 0,
        message: '用户删除成功'
    });
}];
